package com.healthcloud.controller;

import com.healthcloud.entity.*;
import com.healthcloud.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.jsoup.helper.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.healthcloud.utils.DateUtils;
import com.healthcloud.utils.EncryptUtil;
import com.healthcloud.utils.ApiRes;
import com.healthcloud.utils.MessageResource;
import com.healthcloud.utils.PageParam;
import com.healthcloud.vo.PatientVo;
import springfox.documentation.annotations.ApiIgnore;

/**
 * 健康体检数据rest服务控制器
 * Created by xiam on 2015/6/22.
 * Updated by ZhengL on 2015/07/24
 */
@ApiIgnore
@Api(value = "示例说明", description = "健康体检数据rest服务控制器")
@RestController
@RequestMapping("/app")
public class HealthExamApiController {

	@Autowired
	private HealthExamService healthExamService;
	@Autowired
	private DictService dictService;
//	@Autowired
//	private TestReferenceValueService testReferenceValueService;
	@Autowired
    private PatientService patientService;
	@Autowired
	private ExamTestProjectKindConclusionService examTestProjectKindConclusionService;
	@Autowired
	private DoctorAndPatientsRelationService daprService;
	@Autowired
	private TestProjectService testProjectService;
	@Autowired
	private ExternalService externalService;
	@Autowired
	private SignPatientService signService;
	@Autowired
    private AreaCodeService areaCodeService;
	@Autowired
	private InstrumentInstallService instrumentInstallService;
//	@Autowired
//	private HospitalService hospitalService;
//	@Autowired
//	private ChronicService chronicService;
	
	private String[] resultValue = {};
	private String[] examValue = {};
	private String[] resultValue4Search = {};
	private String[] examValue4Search = {};
	private String[] datadictionaryValue = {};
	private String[] examKindConclusionValue = {};

	/**
	 * 上传体检信息
	 * @param request
	 * @return JsonMsg
	 */
	@ApiOperation(value = "上传体检信息",notes ="上传体检信息")
	@RequestMapping(value = "/Physicalexam/set", method = RequestMethod.POST)
	public Object postPhysicalExam(HttpServletRequest request) {
		String res = MessageResource.getMessage("examValue");
		if(StringUtils.isNotBlank(res)){
			examValue = res.trim().toString().split(",");
		}
		Map<String, String> dataMap = getDataMap(request,examValue);
		ApiRes jm = new ApiRes(null);
		String idCard = dataMap.get("idCard");
		String docId = dataMap.get("doctorId");
		String mkCode = dataMap.get("mkExamCode");
		if(StringUtils.isNotBlank(docId)&&StringUtils.isNotBlank(idCard)){
			daprService.create(null,docId, idCard);//新建医院-医生-病人关系
		}else{
			jm.setMsg("医生ID或病人身份证号为空");
			jm.setSuccess(false);
			return jm;
		}
		if(StringUtils.isNotBlank(mkCode)){
			PhysicalExamCriteria peCri = new PhysicalExamCriteria();
			peCri.setMkExamCode(mkCode);
			List<PhysicalExam> tempList = healthExamService.search4Physical(peCri);
			if(tempList!=null&&tempList.size()>0){
				jm.setMsg("该体检编号已存在!");
				jm.setSuccess(false);
				return jm;
			}else{
				PhysicalExam pe = healthExamService.parseJson4Physical(dataMap);
				jm.setData(pe);
			}
		}
		return jm;
	}

	/**
	 * 上传体检数据
	 * @param request
	 * @return JsonMsg
	 * @throws Exception 
	 */
	@ApiOperation(value = "上传体检数据",notes ="上传体检数据")
	@RequestMapping(value = "/testresult/set", method = RequestMethod.POST)
	public Object postTestResult(HttpServletRequest request) throws Exception {
		request.setCharacterEncoding("utf-8");
		String res = MessageResource.getMessage("resultValue");
		if(StringUtils.isNotBlank(res)){
			resultValue = res.trim().toString().split(",");
		}
		Map<String, String> dataMap = getDataMap(request,resultValue);
		TestResult tRes = healthExamService.parseJson4Instrument(dataMap);
		ApiRes jm = new ApiRes(tRes);
		jm.setSuccess(true);
		return jm;
	}

	/**
	 * 获取医生关联的病人列表
	 * @param request
	 * @return JSON
	 */
	@ApiOperation(value = "获取医生关联的病人列表",notes ="获取医生关联的病人列表")
	@RequestMapping(value = "/Physicalexam/getPatients", method = RequestMethod.POST)
	public Object findPatientsByDoc(HttpServletRequest request){
		List<PatientVo> dataList = new ArrayList<PatientVo>();
		ApiRes jm = new ApiRes(dataList);
		Map<String, String> dataMap = new HashMap<String, String>();
		String res = MessageResource.getMessage("examValue4Search");
		if(StringUtils.isNotBlank(res)){
			examValue4Search = res.trim().toString().split(",");
		}
		dataMap = getDataMap(request,examValue4Search);
		jm = verify(dataMap,jm);
		if(!jm.isSuccess()){
			
		}else{
			String doctorId = dataMap.get("doctorId");
			String range = dataMap.get("range");//病人结果集范围
			if(StringUtils.isBlank(range)){
				range = "0";
			}
			if(doctorId!=null){
				dataList = daprService.findPatientsByRelation(null,doctorId,range);
//				if(dataList.size()==0){//新接口未取到数据的话依然调用原接口
//					dataList = patientService.findByExam(doctorId);
//				}
			}
			jm.setData(dataList);
			jm.setSuccess(true);
		}
		return jm;
	}

	
	/**
	 * 移动端查询体检报告
	 * @param request
	 * @return JsonMsg
	 */
	@ApiOperation(value = "移动端查询体检报告",notes ="移动端查询体检报告")
	@RequestMapping(value = "/Physicalexam/get", method = RequestMethod.POST)
	public Object findPhysicalExam(HttpServletRequest request) {
		List<PhysicalExam> dataList = new ArrayList<PhysicalExam>();
		ApiRes jm = new ApiRes(dataList);
		Map<String, String> dataMap = new HashMap<String, String>();
		String res = MessageResource.getMessage("examValue4Search");
		if(StringUtils.isNotBlank(res)){
			examValue4Search = res.trim().toString().split(",");
		}
		dataMap = getDataMap(request,examValue4Search);
		jm = verify(dataMap,jm);
		if(!jm.isSuccess()){
			
		}else{
			String id = dataMap.get("id");
			String idcard = dataMap.get("idCard");
			String doctorId = dataMap.get("doctorId");
			String examDateFrom = dataMap.get("examDateFrom");
			String examDateTo = dataMap.get("examDateTo");
			PhysicalExamCriteria peCri = new PhysicalExamCriteria();
			peCri.setIdCard(idcard);
			if(StringUtils.isNotBlank(doctorId)){
				peCri.setDoctorId(doctorId);
			}
			if (!StringUtil.isBlank(id)) {
				peCri.setId(new BigDecimal(id));
			}
			if (!StringUtil.isBlank(examDateFrom)) {
				DateTime dtFrom = DateUtils.String2Datetime(examDateFrom+" "+"00:00:00","yyyy-MM-dd HH:mm:ss");
				peCri.setExamDateFrom(dtFrom);
			}
			if (!StringUtil.isBlank(examDateTo)) {
				DateTime dtTo = DateUtils.String2Datetime(examDateTo+" "+"23:59:59","yyyy-MM-dd HH:mm:ss");
				peCri.setExamDateTo(dtTo);
			}
			dataList = healthExamService.search4Physical(peCri);
			jm.setData(dataList);
			jm.setSuccess(true);
		}
		return jm;
	}
	/**
	 * 移动端查询病人体检报告列表按时间分组
	 * @param request
	 * @return JsonMsg
	 */
	@ApiOperation(value = "移动端查询病人体检报告列表按时间分组",notes ="移动端查询病人体检报告列表按时间分组")
	@RequestMapping(value = "/Physicalexam/getList", method = RequestMethod.POST)
	public Object findPhysicalExamList(HttpServletRequest request) {
		List<PatientVo> dataList = new ArrayList<PatientVo>();
		List<PhysicalExam> tempList = new ArrayList<PhysicalExam>();
		ApiRes jm = new ApiRes(dataList);
		Map<String, String> dataMap = new HashMap<String, String>();
		String res = MessageResource.getMessage("examValue4Search");
		if(StringUtils.isNotBlank(res)){
			examValue4Search = res.trim().toString().split(",");
		}
		dataMap = getDataMap(request,examValue4Search);
		jm = verify(dataMap,jm);
		if(!jm.isSuccess()){
			
		}else{
			String id = dataMap.get("id");
			String idcard = dataMap.get("idCard");
			String doctorId = dataMap.get("doctorId");
			String examDateFrom = dataMap.get("examDateFrom");
			String examDateTo = dataMap.get("examDateTo");
			PhysicalExamCriteria peCri = new PhysicalExamCriteria();
			peCri.setIdCard(idcard);
			if(StringUtils.isNotBlank(doctorId)){
				peCri.setDoctorId(doctorId);
			}
			if (StringUtils.isNotBlank(id)) {
				peCri.setId(new BigDecimal(id));
			}
			if (StringUtils.isNotBlank(examDateFrom)) {
				DateTime dtFrom = DateUtils.String2Datetime(examDateFrom+" "+"00:00:00","yyyy-MM-dd HH:mm:ss");
				peCri.setExamDateFrom(dtFrom);
			}
			if (StringUtils.isNotBlank(examDateTo)) {
				DateTime dtTo = DateUtils.String2Datetime(examDateTo+" "+"23:59:59","yyyy-MM-dd HH:mm:ss");
				peCri.setExamDateTo(dtTo);
			}
			tempList = healthExamService.search4Physical(peCri);
			for(PhysicalExam pe:tempList){
				PatientVo pv = new PatientVo();
				pv.setMkExamCode(pe.getMkExamCode());
				pv.setIdCard(pe.getIdCard());
				Date dt = pe.getExamDate();
				if(dt!=null){
					String time = DateUtils.format(DateUtils.Date2Calendar(dt), "yyyy-MM-dd HH:mm:ss");
					pv.setLastExamDate(time);
				}
				dataList.add(pv);
			}
			jm.setData(dataList);
			jm.setSuccess(true);
		}
		return jm;
	}

	/**
	 * 获取体检数据按时间分组
	 * @param request
	 * @return JSON
	 */
	@ApiOperation(value = "获取体检数据按时间分组",notes ="获取体检数据按时间分组")
	@RequestMapping(value = "/testresult/getList", method = RequestMethod.POST)
	public Object findTestResultList(HttpServletRequest request){
		List<Map<String,String>> mapList = new ArrayList<Map<String,String>>();
		ApiRes jm = new ApiRes(mapList);
		String res = MessageResource.getMessage("resultValue4Search");
		if(StringUtils.isNotBlank(res)){
			resultValue4Search = res.trim().toString().split(",");
		}
		Map<String, String> dataMap = getDataMap(request,resultValue4Search);
		jm = verify(dataMap,jm);
		if(!jm.isSuccess()){
			
		}else{
			mapList = healthExamService.findVo2(dataMap);
			jm.setData(mapList);
			jm.setSuccess(true);
		}
		return jm;
	}
	
	/**
	 * 移动端查询体检数据
	 * @param request
	 * @return JsonMsg
	 */
	@ApiOperation(value = "移动端查询体检数据",notes ="移动端查询体检数据")
	@RequestMapping(value = "/testresult/get", method = RequestMethod.POST)
	public Object findTestResult(HttpServletRequest request) {
		List<TestResult> dataList = new ArrayList<TestResult>();
		List<TestResult> tempList = new ArrayList<TestResult>();
		ApiRes jm = new ApiRes(dataList);
		String res = MessageResource.getMessage("resultValue4Search");
		if(StringUtils.isNotBlank(res)){
			resultValue4Search = res.trim().toString().split(",");
		}
		Map<String, String> dataMap = getDataMap(request,resultValue4Search);
		jm = verify(dataMap,jm);
		if(!jm.isSuccess()){
			
		}else{
			TestResultCriteria tc = new TestResultCriteria();
			tc = healthExamService.conditionByJsonMap(dataMap);
			tempList = healthExamService.search4Result(tc);
			for(TestResult temp:tempList){
				Date dt = temp.getTestTime();
				String time = DateUtils.format(DateUtils.Date2Calendar(dt), "yyyy-MM-dd HH:mm:ss");
				temp.setTestTimeStr(time);
				dataList.add(temp);
			}
			jm.setData(dataList);
			jm.setSuccess(true);
		}
		return jm;
	}

	/**
	 * 移动端查询体检数据，按照时间和种类分组
	 * @param request
	 * @return JSON
	 */
	@RequestMapping(value = "/testresult/get2", method = RequestMethod.POST)
	public Object findResultGroupByTime(HttpServletRequest request){
		List<Map<String,String>> mapList = new ArrayList<Map<String,String>>();
		ApiRes jm = new ApiRes(mapList);
		String res = MessageResource.getMessage("resultValue4Search");
		if(StringUtils.isNotBlank(res)){
			resultValue4Search = res.trim().toString().split(",");
		}
		Map<String, String> dataMap = getDataMap(request,resultValue4Search);
		jm = verify(dataMap,jm);
		if(!jm.isSuccess()){
			
		}else{
			mapList = healthExamService.findVo(dataMap);
			//获取健康记录附带体重数据
			if (dataMap.get("testKindCode").equals("102")) {
				dataMap.put("testKindCode", "101");
				dataMap.put("testItemCode", "101007");
				mapList.addAll(healthExamService.findVo(dataMap));

			}
			jm.setData(mapList);
			jm.setSuccess(true);
		}
		return jm;
	}

	/**
	 * 移动端查询体检数据，按照时间和种类分组
	 * @param idCard		身份证号码
	 * @param testTimeFrom	开始时间
	 * @param testTimeTo	结束时间
	 * @return JSON
	 */
	@RequestMapping(value = "/testresult/getSmart", method = RequestMethod.POST)
	public ApiRes getSmart(String idCard, String testTimeFrom, String testTimeTo) {
		List<Map<String,String>> mapList = new ArrayList<Map<String,String>>();//返回值

		List<TestResult> reGroupList = healthExamService.getSmartGroup(idCard, testTimeFrom, testTimeTo);
		List<TestResult> reList = healthExamService.getSmart(idCard, testTimeFrom, testTimeTo);

		for (TestResult reGroup : reGroupList) {
			for (TestResult re : reList) {
				if (reGroup.getTestKindCode().equals(re.getTestKindCode()) && reGroup.getTestKindName().equals(re.getTestKindName()) && reGroup.getTestTimeStr().equals(re.getTestTimeStr())) {
					Map<String,String> map = new HashMap<>();
					map.put("testKindCode", reGroup.getTestKindCode());
					map.put("testKindName", reGroup.getTestKindName());
					map.put("testTime", reGroup.getTestTimeStr());
					map.put(re.getTestItemCode(), re.getTestValue());
					mapList.add(map);
				}
			}
		}
		return new ApiRes(mapList);
	}
	
	/**
	 * 获去每月有体检数据的日期
	 * @param request
	 * @return 
	 */
	@RequestMapping(value = "/testresult/getMonthDate", method = RequestMethod.POST)
	public Object getMonthDate(HttpServletRequest request){
		List<TestResult> results = new ArrayList<TestResult>();
		String res = MessageResource.getMessage("resultValue4Search");
		if(StringUtils.isNotBlank(res)){
			resultValue4Search = res.trim().toString().split(",");
		}
		Map<String, String> dataMap = getDataMap(request,resultValue4Search);
		ApiRes jm = new ApiRes(results);
		jm = verify(dataMap,jm);
		
		if(!jm.isSuccess()){
			
		}else{
			//按照日期分组（DATE_FORMAT仅仅适用于MYSQL）
			String groupBy = "DATE_FORMAT(TestTime,'%Y%m%d')"; 
			List<TestResult> temps = healthExamService.getGroups(dataMap, groupBy);
			if(temps!=null&&temps.size()>0){
				for(TestResult tr:temps){
					Date time = tr.getTestTime();
					String dt = DateUtils.format(DateUtils.Date2Calendar(time), "yyyy-MM-dd");
					tr.setTestTimeStr(dt);
					results.add(tr);
				}
			}
			jm.setData(results);
			jm.setSuccess(true);
		}
		return jm;
	}
	
	//获取请求中的参数
	private Map<String, String> getDataMap(HttpServletRequest request,String[] strs){
		Map<String, String> dataMap = new HashMap<String, String>();
		Map<String, String[]> params = request.getParameterMap();
		for(int i=0;i<strs.length;i++){
			String key = strs[i].trim().toString();
			if (params.containsKey(key)) {
				String[] values = params.get(key);
				dataMap.put(key, values[0].toString());
			}
		}
		return dataMap;
	}
	

	/**
	 * 获取数据字典
	 * @param type
	 * @return JsonMsg
	 */
	@RequestMapping(value = "/datadictionary/get", method = RequestMethod.POST)
	public Object datadictionaryGet(String type) {
		List<Dict> dataList = dictService.findByType(type);
		return new ApiRes(dataList);
	}

	/**
	 * 获取参考值
	 * @return JsonMsg
	 */
//	@RequestMapping(value = "/testReferenceValue/get", method = RequestMethod.POST)
//	public Object testReferenceValueGet() {
//		List<TestReferenceValue> dataList = testReferenceValueService.findByEntityAll(new TestReferenceValue());
//		return new JsonMsg(dataList);
//	}

	/**
	 * 设置健康体检报告小结
	 * @param request
	 * @return JSON
	 */
	@ApiOperation(value = "设置健康体检报告小结",notes ="设置健康体检报告小结")
	@RequestMapping(value = "/testKindConclusion/set", method = RequestMethod.POST)
	public Object testKindConclusionSet(HttpServletRequest request)throws Exception{
		request.setCharacterEncoding("utf-8");
		List<Map<String,String>> mapList = new ArrayList<Map<String,String>>();
		ApiRes jm = new ApiRes(mapList);
		String res = MessageResource.getMessage("examKindConclusionValue");
		if(StringUtils.isNotBlank(res)){
			examKindConclusionValue = res.trim().toString().split(",");
		}
		Map<String, String> dataMap = getDataMap(request,examKindConclusionValue);
		jm = verify(dataMap,jm);
		if(!jm.isSuccess()){
			
		}else{			
			ExamTestProjectKindConclusion ec = new ExamTestProjectKindConclusion();
			String mkExamCode = dataMap.get("mkExamCode");
			String testKindCode = dataMap.get("testKindCode");
			String conclusion = dataMap.get("conclusion");
			if(StringUtils.isNotBlank(mkExamCode)){
				ec.setMkExamCode(mkExamCode);
			}
			if(StringUtils.isNotBlank(testKindCode)){
				ec.setTestKindCode(testKindCode);
			}
			if(StringUtils.isNotBlank(conclusion)){
				ec.setConclusion(conclusion);
			}
			examTestProjectKindConclusionService.save(ec);
			jm.setData(mapList);
			jm.setSuccess(true);
		}
		return jm;
	}
	
	
    //验证方法
	private ApiRes verify(Map<String, String> jsonMap, ApiRes msg){
		String username = jsonMap.get("username");
		String usertype = jsonMap.get("usertype");
		String token = jsonMap.get("token");
		String timestamp = jsonMap.get("timestamp");
		String v = jsonMap.get("v");
		String appid = jsonMap.get("appid");
		String sign = jsonMap.get("sign");
//        if(StringUtil.isBlank(token)){
//        	msg.setSuccess(false);
//        	msg.setError("missing_token");
//        }else{
//        	OauthSubjectWrapper wrapper = cache.get(token);
//        	if (wrapper == null) {
//        		msg.setSuccess(false);
//            	msg.setError("invalid_token");
//			}
//        }
		msg.setSuccess(true);
		return msg;
	}
	
	/**
	 * 新版移动端查询体检数据
	 * @author lixx 20160525
	 * @param request
	 * @return JsonMsg
	 */
	@RequestMapping(value = "/testresult/getListByDay", method = RequestMethod.POST)
	public Object findTestResultByDay(HttpServletRequest request) {
		List<TestResultApp> dataList = new ArrayList<TestResultApp>();
		ApiRes jm = new ApiRes(dataList);
		try{
			Map<String, String[]> params = request.getParameterMap();
			TestResultApp entity = new TestResultApp();
			if (!"".equals(params.get("patientId"))
					&& params.get("patientId") != null) {
				entity.setPatientId(params.get("patientId")[0]);
			}
			if (!"".equals(params.get("IDCard"))
					&& params.get("IDCard") != null) {
				entity.setIdCard(params.get("IDCard")[0]);
			}
			if (!"".equals(params.get("MKMedicalinstrumentId"))
					&& params.get("MKMedicalinstrumentId") != null) {
				entity.setMkMedicalInstrumentId(params
						.get("MKMedicalinstrumentId")[0]);
			}
			if (!"".equals(params.get("DataType"))
					&& params.get("DataType") != null) {
				entity.setDataType(params.get("DataType")[0]);
			}
			if (!"".equals(params.get("TimeFrom"))
					&& params.get("TimeFrom") != null) {
				entity.setTimeFrom(params.get("TimeFrom")[0]);
			}
			if (!"".equals(params.get("TimeTo"))
					&& params.get("TimeTo") != null) {
				entity.setTimeTo(params.get("TimeTo")[0]);
			}
			if (!"".equals(params.get("TestItemCode"))
					&& params.get("TestItemCode") != null) {
				entity.setTestItemCode(params.get("TestItemCode")[0]);
			}
			PageParam pageParam = new PageParam();
			if (!"null".equals(params.get("iDisplayStart"))
					&& params.get("iDisplayStart") != null) {
				pageParam.setiDisplayStart(Integer.parseInt(params
						.get("iDisplayStart")[0]));
			}
			if (!"null".equals(params.get("iDisplayLength"))
					&& params.get("iDisplayLength") != null) {
				pageParam.setiDisplayLength(Integer.parseInt(params
						.get("iDisplayLength")[0]));
			}
			dataList = healthExamService.searchTestResultByDay(entity,pageParam);
			jm.setData(dataList);
			jm.setSuccess(true);
		}catch(Exception e){
			e.printStackTrace();
			jm.setSuccess(false);
			jm.setError("201");
			jm.setMsg("数据库错误");
		}
		return jm;
	}
	
	/**
	 * 新版移动端获取项目子类
	 * @author lixx 20160526
	 * @param request
	 * @return JsonMsg
	 */
	@RequestMapping(value = "/getTestProjectItem", method = RequestMethod.POST)
	public Object findTestProjectItem(HttpServletRequest request,String item){

		List<TestProjectItem> dataList = new ArrayList<TestProjectItem>();
		TestProjectItem ti = new TestProjectItem();
		if (item != null && !"".equals(item) && !"checkAll".equals(item)
				&& !"cancleAll".equals(item)) {
			ti.setTestKindCode(item);
		}
		ApiRes jm = new ApiRes(dataList);
		try{
			dataList = testProjectService.findByEntityAll(ti);
			jm.setData(dataList);
			jm.setSuccess(true);
		}catch(Exception e){
			e.printStackTrace();
			jm.setSuccess(false);
			jm.setError("201");
			jm.setMsg("数据库错误");
		}
		return jm;
	
	}
	/**
	 * 获取大类项目
	 * @author lixx 20160720
	 * @param request
	 * @return JsonMsg
	 */
	@RequestMapping(value = "/getTestProjectKind", method = RequestMethod.POST)
	public Object findTestProjectKind(HttpServletRequest request,String method){

		List<TestProjectKind> dataList = new ArrayList<TestProjectKind>();
		ApiRes jm = new ApiRes(dataList);
		TestProjectKind tk = new TestProjectKind();
		//tk.setmethod 暂时不用
		try{
			dataList = testProjectService.findByEntityAll(tk);
			jm.setData(dataList);
			jm.setSuccess(true);
		}catch(Exception e){
			e.printStackTrace();
			jm.setSuccess(false);
			jm.setError("201");
			jm.setMsg("数据库错误");
		}
		return jm;
	
	}
	
	/**
	 * 获取蓝牙包
	 * @author lixx 20161228
	 * @param request
	 * @return JsonMsg
	 */
	@RequestMapping(value = "/getBluetoothPackage", method = RequestMethod.POST)
	public Object getBluetoothPackage(HttpServletRequest request){
		try {
			request.setCharacterEncoding("utf-8");
			Map<String, String[]> params = request.getParameterMap();
			//验证sign
			String sign = com.healthcloud.utils.StringUtil.stringToNotNull(params.get("sign")[0]);
			String time = com.healthcloud.utils.StringUtil.stringToNotNull(params.get("timestamp")[0]);
			String packageId = com.healthcloud.utils.StringUtil.stringToNotNull(params.get("packageId")[0]);
			if (StringUtil.isBlank(sign) || StringUtil.isBlank(time)
					|| StringUtil.isBlank(packageId)) {
				return new ApiRes(true,null,"101","传入参数不合法");
			}
			if (!EncryptUtil.auth(time+"nbmkcloud", sign)) {
				return new ApiRes(true,null,"102","验证错误");
			}
			BluetoothBean entity = new BluetoothBean();
			entity.setPackageId(Integer.parseInt(packageId));
			List<BluetoothBean> list = externalService.getBluetoothPackage(entity);
			if(list.size() > 0 ){
				return new ApiRes(true,list,null,null);
			}else{
				return new ApiRes(true,null,"401","不可更新");
			}
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			return new ApiRes(false,null,"201","系统错误");
		}
	
	}
	
	
	/**
	 * 获取testproject 大类及包含小类
	 * @author lixx 20170124
	 * @param request
	 * @return JsonMsg
	 */
	@RequestMapping(value = "/getAllTestProjectKind", method = RequestMethod.POST)
	public Object getAllTestProject(HttpServletRequest request){
		try {
			request.setCharacterEncoding("utf-8");
			Map<String, String[]> params = request.getParameterMap();
			//验证sign
			String sign = com.healthcloud.utils.StringUtil.stringToNotNull(params.get("sign")[0]);
			String time = com.healthcloud.utils.StringUtil.stringToNotNull(params.get("timestamp")[0]);
			String sTestKindCode = "";
			if (!"".equals(params.get("testKindCode"))
					&& params.get("testKindCode") != null) {
				sTestKindCode = params.get("testKindCode")[0];
			}
			if (StringUtil.isBlank(sign) || StringUtil.isBlank(time)) {
				return new ApiRes(true,null,"101","传入参数不合法");
			}
			if (!EncryptUtil.auth(time+"nbmkcloud", sign)) {
				return new ApiRes(true,null,"102","验证错误");
			}
			TestProjectKind tpk = new TestProjectKind();
			tpk.setTestKindCode(sTestKindCode);
			List<TestProjectKind> list = testProjectService.findByEntityAll(tpk);
			for(TestProjectKind t : list){
				TestProjectItem ti = new TestProjectItem();
				ti.setTestKindCode(t.getTestKindCode());
				List<TestProjectItem> items = testProjectService.findByEntityAll(ti);
				if(items.size() > 0){
					t.setItems(items);
				}
			}
			if(list.size() > 0 ){
				return new ApiRes(true,list,null,null);
			}
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			return new ApiRes(false,null,"201","系统错误");
		}
		return new ApiRes(false,null,"","");
	}
	
	/**
	 * 获取testproject 获取菜单
	 * @author lixx 20170208
	 * @param request
	 * @return JsonMsg
	 *//*
	@RequestMapping(value = "/getAllCook", method = RequestMethod.POST)
	public Object getAllCook(HttpServletRequest request){
		try {
			request.setCharacterEncoding("utf-8");
			Map<String, String[]> params = request.getParameterMap();
			//验证sign
			String sign = com.healthcloud.utils.StringUtil.stringToNotNull(params.get("sign")[0]);
			String time = com.healthcloud.utils.StringUtil.stringToNotNull(params.get("timestamp")[0]);
			int page = 1;
			int rows = 20;
			String id = "";
			try{
				if (!"".equals(params.get("page"))
						&& params.get("page") != null) {
					page = Integer.parseInt(params.get("page")[0]);
				}
				
				if (!"".equals(params.get("rows"))
						&& params.get("rows") != null) {
					rows = Integer.parseInt(params.get("rows")[0]);
				}
				
				if (!"".equals(params.get("id"))
						&& params.get("id") != null) {
					id = params.get("id")[0];
				}	
			}catch(Exception e){
				e.printStackTrace();
				return new JsonMsg(false,null,"201","参数错误");
			}
			
			PageParam pageParam = new PageParam();
			pageParam.setiDisplayStart((page-1)*rows);
			pageParam.setiDisplayLength(rows);
			List<CookBean> list = externalService.getAllCook(id, pageParam);
			if(list.size() > 0 ){
				return new JsonMsg(true,list,null,null);
			}
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			return new JsonMsg(false,null,"201","系统错误");
		}
		return new JsonMsg(false,null,"","");
	}
	*//**
	 * 获取testproject 获取药品
	 * @author lixx 20170208
	 * @param request
	 * @return JsonMsg
	 *//*
	@RequestMapping(value = "/getAllDrug", method = RequestMethod.POST)
	public Object getAllDrug(HttpServletRequest request){
		try {
			request.setCharacterEncoding("utf-8");
			Map<String, String[]> params = request.getParameterMap();
			//验证sign
			String sign = com.healthcloud.utils.StringUtil.stringToNotNull(params.get("sign")[0]);
			String time = com.healthcloud.utils.StringUtil.stringToNotNull(params.get("timestamp")[0]);
			int page = 1;
			int rows = 20;
			String id = "";
			try{
				if (!"".equals(params.get("page"))
						&& params.get("page") != null) {
					page = Integer.parseInt(params.get("page")[0]);
				}
				
				if (!"".equals(params.get("rows"))
						&& params.get("rows") != null) {
					rows = Integer.parseInt(params.get("rows")[0]);
				}
				
				if (!"".equals(params.get("id"))
						&& params.get("id") != null) {
					id = params.get("id")[0];
				}	
			}catch(Exception e){
				e.printStackTrace();
				return new JsonMsg(false,null,"201","参数错误");
			}
			
			PageParam pageParam = new PageParam();
			pageParam.setiDisplayStart((page-1)*rows);
			pageParam.setiDisplayLength(rows);
			List<DrugBean> list = externalService.getAllDrug(id,pageParam);
			if(list.size() > 0 ){
				return new JsonMsg(true,list,null,null);
			}
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			return new JsonMsg(false,null,"201","系统错误");
		}
		return new JsonMsg(false,null,"","");
	}
	
	*//**
	 * 签约病人 申请
	 * @author lixx 20160525
	 * @param request
	 * @return JsonMsg
	 */
	@RequestMapping(value = "/sign/apply", method = RequestMethod.POST)
	public Object signApply(HttpServletRequest request) {
		try{
			Map<String, String[]> params = request.getParameterMap();
			String sign = com.healthcloud.utils.StringUtil.stringToNotNull(params.get("sign")[0]);
			String time = com.healthcloud.utils.StringUtil.stringToNotNull(params.get("timestamp")[0]);
			String method = com.healthcloud.utils.StringUtil.stringToNotNull(params.get("method")[0]);
			if (StringUtil.isBlank(sign) || StringUtil.isBlank(time)
					|| StringUtil.isBlank(method)) {
				return new ApiRes(true,null,"101","传入参数不合法");
			}
			if (!EncryptUtil.auth(time+"nbmkcloud", sign)) {
				return new ApiRes(true,null,"102","验证错误");
			}
			SignPatientBean entity = new SignPatientBean();
			if (!"".equals(params.get("patientIdCard"))
					&& params.get("patientIdCard") != null) {
				entity.setPatientIdCard(params.get("patientIdCard")[0]);
			}
			if (!"".equals(params.get("doctorId"))
					&& params.get("doctorId") != null) {
				entity.setDoctorId(params.get("doctorId")[0]);
			}
			if(method.equals("apply")){
				//判断是否已经申请
				List<SignPatientBean> list = signService.signSearch(entity,null,null);
				int i = 0;
				entity.setStatus("0");
				if(list.size() == 0){
					i = signService.signApply(entity);
				}else{
					i = signService.signUpdate(entity);
				}
				if(i > 0){
					return new ApiRes(true, null, "0", "成功");
				}else{
					return new ApiRes(false, null, "201", "数据库错误");
				}
				
			}else if(method.equals("agree")){
				if (!"".equals(params.get("id"))
						&& params.get("id") != null) {
					entity.setId(Integer.parseInt(params.get("id")[0]));
				}
				entity.setStatus("1");
				int i = signService.signAgree(entity);
				if(i > 0){
					return new ApiRes(true, null, "0", "成功");
				}else{
					return new ApiRes(false, null, "201", "数据库错误");
				}
			}else if(method.equals("refuse")){
				if (!"".equals(params.get("id"))
						&& params.get("id") != null) {
					entity.setId(Integer.parseInt(params.get("id")[0]));
				}
				entity.setStatus("3");
				int i = signService.signRefuse(entity);
				if(i > 0){
					return new ApiRes(true, null, "0", "成功");
				}else{
					return new ApiRes(false, null, "201", "数据库错误");
				}
			}else if(method.equals("cancel")){
				if (!"".equals(params.get("id"))
						&& params.get("id") != null) {
					entity.setId(Integer.parseInt(params.get("id")[0]));
				}
				entity.setStatus("2");
				int i = signService.signCancel(entity);
				if(i > 0){
					return new ApiRes(true, null, "0", "成功");
				}else{
					return new ApiRes(false, null, "201", "数据库错误");
				}
			}else if(method.equals("search")){
				List<SignPatientBean> list = signService.signSearch(entity,null,null);
				return new ApiRes(true, list, "", "");
			}
			
		}catch(Exception e){
			e.printStackTrace();
			return new ApiRes(false, null, "201", "数据库错误");
		}
		return new ApiRes(true, null, "0", "成功");
	}
	
	@RequestMapping(value = "/getPatients", method = RequestMethod.POST)
	public Object getPatients(HttpServletRequest request){
		try {
			request.setCharacterEncoding("utf-8");
			Map<String, String[]> params = request.getParameterMap();
			//验证sign
			String sign = com.healthcloud.utils.StringUtil.stringToNotNull(params.get("sign")[0]);
			String time = com.healthcloud.utils.StringUtil.stringToNotNull(params.get("timestamp")[0]);
			String doctorId = "";
			try{
				if (!"".equals(params.get("doctorId"))
						&& params.get("doctorId") != null) {
					doctorId = params.get("doctorId")[0];
				}
			}catch(Exception e){
				e.printStackTrace();
				return new ApiRes(false,null,"201","参数错误");
			}
			
			List<PatientVo> list = externalService.getPatients(doctorId);
			if(list.size() > 0 ){
				return new ApiRes(true,list,null,null);
			}
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			return new ApiRes(false,null,"201","系统错误");
		}
		return new ApiRes(false,null,"","");
	}
	
	/**
	 * 调用者: app
     * 根据code，level获取下级地区列表
     */
    @RequestMapping(value = "/getLowerAreaList")
    public @ResponseBody List<AreaCode> getLowerAreaList(HttpServletResponse response,String code, String level) {
        List<AreaCode> areaCodeList = areaCodeService.getLowerAreaList(code, level);
//        try {
//            response.getWriter().write(JSONArray.fromObject(areaCodeList).toString());
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
        return areaCodeList;
    }
    
    /**
	 * 调用者: app
     * 获取地区医院
     *//*
    @RequestMapping(value = "/getHospitalList", method = RequestMethod.POST)
	public @ResponseBody List<Hospital> getHospitalList(String areaCode){
		List<Hospital> list = hospitalService.getHospitalListByAreaCode(areaCode, null);
		return list;
	}
    
    *//**
	 * 调用者: app
     * 获取医院下的医生
     *//*
    @RequestMapping(value = "/getDrByHosp", method = RequestMethod.POST)
	public @ResponseBody JsonMsg getDrByHosp(HttpServletRequest request){
    	try{
    		Map<String, String[]> params = request.getParameterMap();
			String sign = com.healthcloud.utils.StringUtil.stringToNotNull(params.get("sign")[0]);
			String time = com.healthcloud.utils.StringUtil.stringToNotNull(params.get("timestamp")[0]);
			String hospId = com.healthcloud.utils.StringUtil.stringToNotNull(params.get("hospId")[0]);

			if (StringUtil.isBlank(sign) || StringUtil.isBlank(time)
					|| StringUtil.isBlank(hospId)) {
				return new JsonMsg(false, null, "101", "传入参数不合法");
			}
			if (!EncryptUtil.auth(time+"nbmkcloud", sign)) {
				return new JsonMsg(false,null,"102","验证错误");
			}
			DoctorBean bean = new DoctorBean();
			bean.setHospId(hospId);
			List<DoctorBean> list = signService.searchDrByHosp(bean);
			return new JsonMsg(true, list, "00", "成功");
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			return new JsonMsg(false,null,"201","系统错误");
		}
	}
    
    *//**
	 * 获取全部血糖数据(包括从gprs版的血糖仪以及蓝牙血糖仪的数据)
     *//*
    @RequestMapping(value = "/getAllBsData", method = RequestMethod.POST)
	public @ResponseBody JsonMsg getAllBsData(HttpServletRequest request){
    	try{
    		Map<String, String[]> params = request.getParameterMap();
			String sign = com.healthcloud.utils.StringUtil.stringToNotNull(params.get("sign")[0]);
			String time = com.healthcloud.utils.StringUtil.stringToNotNull(params.get("timestamp")[0]);
			String idCard = com.healthcloud.utils.StringUtil.stringToNotNull(params.get("idCard")[0]);
			String pageSize = com.healthcloud.utils.StringUtil.stringToNotNull(params.get("pageSize")[0]);
			String pageNumber = com.healthcloud.utils.StringUtil.stringToNotNull(params.get("pageNumber")[0]);
			if (StringUtil.isBlank(sign) || StringUtil.isBlank(time)
					|| StringUtil.isBlank(idCard)) {
				return new JsonMsg(false, null, "101", "传入参数不合法");
			}
			if (!EncryptUtil.auth(time+"nbmkcloud", sign)) {
				return new JsonMsg(false,null,"102","验证错误");
			}
			if(StringUtil.isBlank(pageSize)){
				pageSize = "10";
			}
			if(StringUtil.isBlank(pageNumber)){
				pageSize = "1";
			}
			int iIndex = Integer.parseInt(pageSize)*(Integer.parseInt(pageNumber)-1);
			//请求租赁系统，通过idcard获得相关sn
			List<String> sns = HttpUtil.findSNByIdCard(idCard);
			CommonTestResultBean bean = new CommonTestResultBean();
			bean.setIdCard(idCard);
			if(sns.size() > 0){
				bean.setSN(sns.toString());
			}
			List<CommonTestResultBean> list = chronicService.getAllBsData(sns,bean,
					String.valueOf(iIndex), pageSize);
			return new JsonMsg(true, list, "00", "成功");
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			return new JsonMsg(false,null,"201","系统错误");
		}
	}
    
    *//**
	 * 获取全部血压数据(包括从gprs版的血压以及蓝牙血压的数据)
     *//*
    @RequestMapping(value = "/getAllBpData", method = RequestMethod.POST)
	public @ResponseBody JsonMsg getAllBpData(HttpServletRequest request){
    	try{
    		Map<String, String[]> params = request.getParameterMap();
			String sign = com.healthcloud.utils.StringUtil.stringToNotNull(params.get("sign")[0]);
			String time = com.healthcloud.utils.StringUtil.stringToNotNull(params.get("timestamp")[0]);
			String idCard = com.healthcloud.utils.StringUtil.stringToNotNull(params.get("idCard")[0]);
			String pageSize = com.healthcloud.utils.StringUtil.stringToNotNull(params.get("pageSize")[0]);
			String pageNumber = com.healthcloud.utils.StringUtil.stringToNotNull(params.get("pageNumber")[0]);
			if (StringUtil.isBlank(sign) || StringUtil.isBlank(time)
					|| StringUtil.isBlank(idCard)) {
				return new JsonMsg(false, null, "101", "传入参数不合法");
			}
			if (!EncryptUtil.auth(time+"nbmkcloud", sign)) {
				return new JsonMsg(false,null,"102","验证错误");
			}
			if(StringUtil.isBlank(pageSize)){
				pageSize = "10";
			}
			if(StringUtil.isBlank(pageNumber)){
				pageSize = "1";
			}
			int iIndex = Integer.parseInt(pageSize)*(Integer.parseInt(pageNumber)-1);
			//请求租赁系统，通过idcard获得相关sn
			List<String> sns = HttpUtil.findSNByIdCard(idCard);
			CommonTestResultBean bean = new CommonTestResultBean();
			bean.setIdCard(idCard);
			List<CommonTestResultBean> list = chronicService.getAllBpData(sns,bean,
					String.valueOf(iIndex), pageSize);
			return new JsonMsg(true, list, "00", "成功");
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			return new JsonMsg(false,null,"201","系统错误");
		}
	}*/
    
    
	/**
	 * 跳转接口授权登录失败
	 * @author lixx 20170324
	 */
	@RequestMapping(value = "/toError")
	public Object toError(Model model){
		return "newframe/error";
	}


	/**
	 * 调用者: app
	 * 获取医院下的医生
	 */
	@RequestMapping(value = "/getDrByHosp", method = RequestMethod.POST)
	public @ResponseBody
    ApiRes getDrByHosp(HttpServletRequest request){
		try{
			Map<String, String[]> params = request.getParameterMap();
			String sign = com.healthcloud.utils.StringUtil.stringToNotNull(params.get("sign")[0]);
			String time = com.healthcloud.utils.StringUtil.stringToNotNull(params.get("timestamp")[0]);
			String hospId = com.healthcloud.utils.StringUtil.stringToNotNull(params.get("hospId")[0]);

			if (StringUtil.isBlank(sign) || StringUtil.isBlank(time)
					|| StringUtil.isBlank(hospId)) {
				return new ApiRes(false, null, "101", "传入参数不合法");
			}
			if (!EncryptUtil.auth(time+"nbmkcloud", sign)) {
				return new ApiRes(false,null,"102","验证错误");
			}
			DoctorBean bean = new DoctorBean();
			bean.setHospId(hospId);
			List<DoctorBean> list = signService.searchDrByHosp(bean);
			return new ApiRes(true, list, "00", "成功");
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			return new ApiRes(false,null,"201","系统错误");
		}
	}

	/**
	 * 调用者: app
	 * 根据医生id获取医院中的设备
	 */
	@RequestMapping(value = "/getInstrumentByDoctorId", method = RequestMethod.POST)
	public @ResponseBody
    ApiRes getInstrumentByDoctorId(Long id){
		try{
			List<InstrumentInstallEntity> list = instrumentInstallService.queryByDoctorId(id);
			return new ApiRes(true, list, "00", "成功");
		} catch (Exception e1) {
			e1.printStackTrace();
			return new ApiRes(false,null,"201","系统错误");
		}
	}


}
